<template>
  <div class="real-name-auth">
    <!-- 返回按钮 -->
    <div class="back-icon" @click="$routerouter.back()">
      <el-icon class="icon"><ArrowLeft /></el-icon>
    </div>

    <!-- 页面标题区 -->
    <div class="auth-header">
      <h2 class="auth-title">身份证实名认证</h2>
      <p class="auth-desc">信息将严格保密，仅用于身份验证</p>
    </div>

    <!-- 已认证：显示脱敏信息（无表单） -->
    <div v-if="userInfo.status === '1'" class="certified-success">
      <div class="success-icon-wrap">
        <el-icon class="success-icon"><SuccessFilled  /></el-icon>
      </div>
      <h3 class="success-title">您已完成实名认证</h3>
      <div class="certified-info">
        <p><span class="info-label">真实姓名：</span>{{ hideRealName(userInfo.realName) }}</p>
        <p><span class="info-label">身份证号：</span>{{ hideIdCard(userInfo.idCard) }}</p>
      </div>
      <el-button
          type="primary"
          class="back-center-btn"
          @click="$router.push('/myDetail')"
      >
        返回个人中心
      </el-button>
    </div>

    <!-- 未认证：显示认证表单 -->
    <div v-else class="certify-form-wrap">
      <el-form
          :model="authForm"
          :rules="authRules"
          ref="authFormRef"
          label-width="120px"
          class="auth-form"
      >
        <!-- 姓名输入 -->
        <el-form-item label="姓名" prop="realName" class="form-item">
          <el-input
              v-model="authForm.realName"
              placeholder="请输入身份证姓名"
              maxlength="20"
              class="auth-input"
              :disabled="isSubmitting"
          />
        </el-form-item>

        <!-- 身份证号输入 -->
        <el-form-item label="身份证号" prop="idCard" class="form-item">
          <el-input
              v-model="authForm.idCard"
              placeholder="请输入18位身份证号（最后一位可填X）"
              maxlength="18"
              class="auth-input"
              :disabled="isSubmitting"
              @input="handleIdCardInput"
          />
        </el-form-item>

        <!-- 身份证正面上传 -->
        <el-form-item label="身份证正面" prop="frontImg" class="form-item">
          <el-upload
              class="idcard-uploader"
              :action="''"
              :http-request="(params) => handleUpload(params, 'frontImg')"
              :before-upload="beforeImgToBase64"
              :show-file-list="false"
              accept="image/jpeg,image/png"
              :disabled="isSubmitting"
          >
            <div class="upload-container">
              <div v-if="authForm.frontImg" class="uploaded-wrap">
                <img :src="frontImgUrl" class="uploaded-img" alt="身份证正面" />
                <el-button type="text" class="reupload-btn" @click="clearImg('frontImg')">重新上传</el-button>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <p class="upload-tip">点击上传身份证正面</p>
                <p class="upload-desc">需清晰拍摄：姓名、头像、证件号区域</p>
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 身份证反面上传 -->
        <el-form-item label="身份证反面" prop="backImg" class="form-item">
          <el-upload
              class="idcard-uploader"
              :action="''"
              :http-request="(params) => handleUpload(params, 'backImg')"
              :before-upload="beforeImgToBase64"
              :show-file-list="false"
              accept="image/jpeg,image/png"
              :disabled="isSubmitting"
          >
            <div class="upload-container">
              <div v-if="authForm.backImg" class="uploaded-wrap">
                <img :src="backImgUrl" class="uploaded-img" alt="身份证反面" />
                <el-button type="text" class="reupload-btn" @click="clearImg('backImg')">重新上传</el-button>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <p class="upload-tip">点击上传身份证反面</p>
                <p class="upload-desc">需清晰拍摄：有效期、国徽区域</p>
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 提交认证按钮 -->
      <el-button
          type="success"
          @click="submitAuth"
          class="submit-btn"
          :loading="isSubmitting"
      >
        提交实名认证
      </el-button>
    </div>
  </div>
</template>

<script>
import { ArrowLeft, Plus, SuccessFilled  } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { cardVerify, getUser } from '../api/user.js'

export default {
  name: "Certification",
  components: { ArrowLeft, Plus, SuccessFilled  },
  data() {
    return {
      userInfo: {}, // 存储用户状态（判断是否已认证）
      authForm: {
        realName: '',       // 姓名
        idCard: '',         // 身份证号
        frontImg: '',       // 身份证正面（纯Base64）
        backImg: ''         // 身份证反面（纯Base64）
      },
      authRules: {
        realName: [
          { required: true, message: '请输入身份证姓名', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]{2,20}$/, message: '请输入2-20位中文姓名', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入18位有效身份证号', trigger: 'blur' }
        ],
        frontImg: [
          { required: true, message: '请上传身份证正面', trigger: 'change' }
        ],
        backImg: [
          { required: true, message: '请上传身份证反面', trigger: 'change' }
        ]
      },
      isSubmitting: false, // 提交加载状态
      frontImgUrl: '',     // 正面预览图（带Base64前缀）
      backImgUrl: ''       // 反面预览图（带Base64前缀）
    }
  },
  methods: {
    // 1. 初始化：读取用户最新状态
    async initUserStatus() {
      try {
        let {data: data} = await getUser()
        if (data.code === 200) {
          this.userInfo = data.data
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        } else {
          const localUser = localStorage.getItem('userInfo')
          if (localUser) {
            this.userInfo = JSON.parse(localUser)
          }
        }
      } catch (error) {
        // 网络异常时读取缓存
        const localUser = localStorage.getItem('userInfo')
        if (localUser) {
          this.userInfo = JSON.parse(localUser)
        }
        ElMessage.warning('获取用户状态失败，将使用本地缓存')
      }
    },
    handleIdCardInput() {
      if (this.authForm.idCard) {
        const validInput = this.authForm.idCard.replace(/[^0-9Xx]/g, '').toUpperCase()
        this.authForm.idCard = validInput.substring(0, 18)
      }
    },

    // 3. 清除上传的图片
    clearImg(type) {
      this.authForm[type] = ''
      this[type + 'Url'] = ''
    },

    // 4. 图片格式/大小校验
    beforeImgToBase64(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        ElMessage.error('请上传JPG或PNG格式的图片')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB')
        return false
      }
      return true
    },

    // 5. 图片转为Base64（用于预览和提交）
    handleUpload(params, type) {
      const file = params.file
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const fullBase64 = e.target.result // 完整Base64（含前缀，用于预览）
          if (typeof fullBase64 !== 'string') {
            throw new Error('图片编码格式错误')
          }
          // 提取纯Base64（无前缀，用于提交后端）
          const pureBase64 = fullBase64.split(',')[1]

          // 更新表单数据和预览图
          this.authForm[type] = pureBase64
          this[type + 'Url'] = fullBase64

          // 提示上传成功
          const tip = type === 'frontImg' ? '身份证正面' : '身份证反面'
          ElMessage.success(`${tip}上传成功`)
          params.onSuccess() // 通知el-upload上传完成
        } catch (error) {
          ElMessage.error('图片处理失败，请重试')
          console.error('图片编码错误：', error)
          params.onError(error) // 通知el-upload上传失败
        }
      }
      // 读取文件为Base64格式
      reader.readAsDataURL(file)
    },

    // 6. 提交实名认证（核心：同步状态并跳转）
    async submitAuth() {
      // 表单校验
      const isFormValid = await new Promise((resolve) => {
        this.$refs.authFormRef.validate((valid) => resolve(valid))
      })
      if (!isFormValid) return

      try {
        this.isSubmitting = true
        const submitParams = {
          name: this.authForm.realName,
          card: this.authForm.idCard,
          frontImg: this.authForm.frontImg,
          backImg: this.authForm.backImg
        }

        // 调用认证接口
        let {data: data} = await cardVerify(submitParams)
        if (data.code === 200) {
          // 认证成功：1. 更新用户状态 2. 同步缓存 3. 跳转个人中心
          this.userInfo.status = '1' // 标记为已认证
          this.userInfo.realName = this.authForm.realName // 存储姓名（用于脱敏）
          this.userInfo.idCard = this.authForm.idCard // 存储身份证号（用于脱敏）
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

          ElMessage.success({
            message: '身份证实名认证已通过',
            duration: 1500,
            onClose: () => {
              this.$router.push('/myDetail') // 跳转回个人中心
            }
          })
        } else {
          ElMessage.error('认证失败：' + (data.msg || '请检查信息后重试'))
        }
      } catch (error) {
        ElMessage.error('网络异常，认证请求失败，请稍后重试')
        console.error('认证接口错误：', error)
      } finally {
        this.isSubmitting = false
      }
    },

    // 7. 姓名脱敏：显示第一个字，其余用*代替（如：张**）
    hideRealName(name) {
      if (!name) return '已隐藏'
      return name.replace(/(\S)\S+/, '$1**')
    },

    // 8. 身份证号脱敏：显示前6后4，中间用*代替（如：110101********1234）
    hideIdCard(idCard) {
      if (!idCard) return '已隐藏'
      return idCard.replace(/^(\d{6})(\d{8})(\d{4})$/, '$1********$3')
    }
  },
  mounted() {
    // 页面加载时初始化用户状态
    this.initUserStatus()
  }
}
</script>

<style scoped>
/* 全局容器 */
.real-name-auth {
  width: 100%;
  max-width: 500px;
  margin: 30px auto;
  padding: 0 20px;
  box-sizing: border-box;
  font-size: 14px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  padding-top: 20px;
}

/* 返回按钮 */
.back-icon {
  margin-bottom: 20px;
  cursor: pointer;
  color: #666;
}
.back-icon .icon { font-size: 20px; }

/* 标题区 */
.auth-header {
  margin-bottom: 30px;
  text-align: center;
}
.auth-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px;
}
.auth-desc {
  font-size: 13px;
  color: #666;
  margin: 0;
}

/* 已认证成功样式 */
.certified-success {
  background-color: #fff;
  padding: 40px 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  text-align: center;
  margin-bottom: 30px;
}
.success-icon-wrap { margin-bottom: 16px; }
.success-icon {
  font-size: 48px;
  color: #67C23A; /* 成功绿色 */
}
.success-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 24px;
}
.certified-info {
  text-align: left;
  margin: 0 10px 32px;
  font-size: 16px;
  color: #666;
}
.info-label {
  color: #333;
  font-weight: 500;
  display: inline-block;
  width: 80px;
}
.certified-info p { margin-bottom: 12px; }
.back-center-btn { width: 100%; height: 46px; border-radius: 8px; }

/* 未认证表单容器 */
.certify-form-wrap {
  background-color: #fff;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

/* 表单项样式（与之前保持一致） */
.form-item { margin-bottom: 25px; }
.auth-input {
  height: 44px;
  border-radius: 8px;
  border-color: #eee;
}
.auth-input:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 图片上传样式（与之前保持一致） */
.idcard-uploader { display: block; }
.upload-container {
  width: 100%;
  height: 180px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}
.uploaded-wrap { width: 100%; height: 100%; position: relative; }
.uploaded-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
.reupload-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 0;
  border-radius: 0 0 8px 8px;
}
.reupload-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
}
.upload-placeholder {
  width: 100%;
  height: 100%;
  background-color: #fafafa;
  border: 2px dashed #eee;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}
.upload-placeholder:hover { border-color: #409EFF; }
.upload-icon {
  font-size: 24px;
  color: #999;
  margin-bottom: 8px;
}
.upload-tip {
  font-size: 14px;
  color: #666;
  margin: 0 0 4px;
}
.upload-desc {
  font-size: 12px;
  color: #999;
  margin: 0;
  text-align: center;
  padding: 0 10px;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 46px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
}

/* 移动端适配 */
@media (max-width: 375px) {
  .auth-form { padding: 20px; }
  .form-item { margin-bottom: 20px; }
  .upload-container { height: 150px; }
  .auth-title { font-size: 20px; }
}
</style>